<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
		<title>版本升级</title>
		<link rel="stylesheet" href="../../css/hui_native.css" />
		<style>
			.hui-wrap,
			body {
				background: #FFFFFF;
				
			}
			/*.circle {
				width: 200px;
				height: 200px;
			}
			
			.circles-wrp {
				width: 200px;
				height: 200px;
			}*/
			
			.circles-text {
				font-size: 40px !important;
			}
		</style>
	</head>

	<body style="">
		<header class="hui-header">
			<div id="hui-back"></div>
			<h1>固件升级</h1>
				
				

		</header>
		
		
		<div class="hui-wrap">
			<div id="datas">
				<div style="display: flex;justify-content: center;width: 100vw;margin:30px 0px 10px 0px">
					<div class="circle" id="circles-1"></div>
				</div>

				<div v-if="!needUpdate" style="display: flex;flex-direction: column;padding:10px 16px;align-items: center;">
					<button @click="getNowVersion" class="hui-button " style="width: 200px;">检查更新</button>
					<p v-if="versionUpdate" style="color: #333333;padding-top:10px;" v-text="'最新版本:' + versionUpdate.firmware"></p>
				</div>

				<div v-if="needUpdate && !updating" style="display: flex;flex-direction: column;padding:10px 16px;align-items: center;">
					<button @click="updateFromNet" class="hui-button" style="width: 200px;color: #FFFFFF;background: #c33b43;" >下载更新</button>
					<p style="color: #C33B43;padding-top:10px;" v-text="'最新版本:' + versionUpdate.firmware"></p>
				</div>

				<div v-if="needUpdate && updating" style="display: flex;flex-direction: column;padding:10px 16px;align-items: center;">
					<button @click="updateFromNet" class="hui-button" style="width: 200px;" disabled="true">正在更新中...</button>
					<p style="color: #C33B43;padding-top:10px;" v-text="'最新版本:' + versionUpdate.firmware"></p>
				</div>

				<div style="padding: 16px;border-top: #E3E3E3 1px solid;">
					<p v-text="'当前版本:  ' +nowVersion"></p>
				</div>

			</div>
		</div>
		
			<script type="text/javascript" src="../../js/app/ble.js"></script>

		<script type="text/javascript" src="../../libs/hui.js"></script>
		<script type="text/javascript" src="../../libs/vue.js"></script>
		<script type="text/javascript" src="../../js/md5.js"></script>
		<script type="text/javascript" src="../../js/app/circles.min.js"></script>
		<!--<script type="text/javascript" src="base64.min.js"></script>-->
		

		<script type="text/javascript" src="../../js/jquery.1.9.1.min.js"></script>
		<script type="text/javascript" src="../../js/app/url.js"></script>
		<script type="text/javascript" src="../../js/md5.js"></script>


		<script type="text/javascript" src="../../js/app/api.js"></script>

		<script type="text/javascript">
			var myCircle;

			hui.ready(function() {
				myCircle = Circles.create({
					id: 'circles-1',
					radius: 120,
					value: 0,
					maxValue: 100,
					width: 15,
					text: function(value) {
						return value == 0 ? "" : value + '%';
					},
					colors: ['#F3F3F3', '#c33b43'],
					textClass: 'circles-text',
				});

				hui.plusReady(function() {
					if(vm) {
						vm.getNowVersion();
					}

				})
			})

			function setPrecent(percentage) {
				myCircle.update(percentage, 250);
			}

			var vm = new Vue({
				el: '#datas',
				data: {
					Tid: "", //终端编号
					mac: "", //设备mac地址
					bleConnect: null,

					packageList: [],
					packageCount: 0, //分包总数
					packageIndex: -1, //正在传送的分包号

					lastPrecent: 0,
					errCount: 0,

					nowVersion: "",
					needUpdate: false, //是否需要升级
					updating: false, //是否正在升级
					versionUpdate: null, //升级内容

				},
				mounted: function() {
					var _self = this;
//					this.Tid = getValue('tid');
//					this.mac = getValue('mac');
					
					
					
						var zd_id = localStorage.getItem("zd_id");
						this.Tid = zd_id;
						this.mac =  localStorage.getItem("mac");
				

					console.log(this.Tid + "|" + this.mac);

				},

				methods: {
					getPrecentText: function() {
						var str = "";
						var precent = this.getPrecent();
						if(precent > 0) {
							str = precent + "%[" + (this.packageIndex + 1) + "/" + this.packageCount + "]";
						}
						return str;
					},

					getPrecent: function() {
						var precent = 0;
						if(this.packageCount == 0 || this.packageIndex == -1) {} else {
							precent = parseInt(this.packageIndex / this.packageCount * 100);
						}
						return precent;
					},

					//获取本地固件版本
					getNowVersion: function() {
						var _self = this;
						if(!this.Tid || this.Tid.length == 0) {
							hui.toast("请先获取终端编号");
							return;
						}

						if(!_self.bleConnect) {
							_self.bleConnect = plus.blecontroler;
						}

						var command = "5A4008" + this.Tid;
						console.log(command);
						this.bleConnect.writeData(command, function(ret) {
							console.log(ret);
							var left = ret.substr(ret.length - 6, 2)
							var right = ret.substr(ret.length - 4, 2)
							var v = parseInt(left,16) + "." + parseInt(right,16)

							console.log(v);
							_self.nowVersion = v;
							_self.checkVersion();
						}, function(err) {
							hui.closeLoading();
							alert(err);
						})
					},

					//查询网络固件版本
					checkVersion: function() {
						var _self = this;
						var path = urlManager.getFirmware();
						console.log(path);
						var username = localStorage.getItem("username");
						var sec = localStorage.getItem("sec_pwd");
						var time = apiManage.getNow();
						var key = "loginName=" + username + "&passWord=" + sec + "&time=" + time;
						//				console.log(key);
						var paramKey = hex_md5(key);

						var readyParam = {
							cusId: apiManage.getCompanyId(),
							status: "0"
						};

						hui.loading();

						$.ajax({
							type: "POST",
							data: readyParam,
							url: path + "&time=" + time,
							beforeSend: function(request) {
								request.setRequestHeader("loginName", username);
								request.setRequestHeader("time", time);
								request.setRequestHeader("sign", paramKey);
							},
							success: function(result) {
								hui.closeLoading();
								console.log("版本库文件接口============================" + JSON.stringify(result));
								var sp = {};
								sp.firmware = result.version;
								sp.updateTime = result.createDateStr.substring(0, 10);
								sp.updateUrl = result.url;
								_self.versionUpdate = sp;

								if(result.version != _self.nowVersion) {
									_self.needUpdate = true;
								} else {
									 hui.toast("已是最新版本:" + result.version);
									_self.needUpdate = false;
								}

							}
						});
					},

					//下载升级文件
					updateFromNet: function() {
						var _self = this;
						var fileUrl = _self.versionUpdate.updateUrl;

						var saveName = "_downloads/";
						hui.loading("正在下载更新包...");
						var dtask = plus.downloader.createDownload(fileUrl, {
							filename: saveName
						}, function(d, status) {
							// 下载完成
							if(status == 200) {
								//alert("Download success: " + d.filename);
								hui.closeLoading();
								var filePath = d.filename;
								console.log("文件下载成功:" + filePath);
								plus.io.resolveLocalFileSystemURL(filePath, function(fs) {
									console.log(fs.fullPath);
									_self.updateFromFile(fs.fullPath);
								});
							} else {
								hui.closeLoading();
								alert("Download failed: " + status);
							}
						});
						//dtask.addEventListener("statechanged", onStateChanged, false);
						dtask.start();
					},

					//开始升级
					updateFromFile: function(path) {
						var _self = this;
						_self.bleConnect.getHexFromFile(path, function(ret) {
							var list = JSON.parse(ret);
							console.log("返回数据:" + list.length);

							_self.packageList = list;
							_self.packageCount = list.length;

							_self.updateStart();
						}, function(err) {
							hui.closeLoading();
							alert(err);
						});

					},

					//开始升级
					updateStart: function() {
						var _self = this;
						if(!this.Tid || this.Tid.length == 0) {
							hui.toast("请先获取终端编号");
							return;
						}

						var command = "5A3009" + this.Tid + "AA";
						console.log("开始升级" + command);
						this.bleConnect.writeData(command, function(ret) {
							console.log("返回数据:" + ret);
							if(checkCommand(ret)) {
								setPrecent(0);
								hui.loading("正在准备升级...")
								setTimeout(function() {
									hui.closeLoading();
									_self.updateing(0);
								}, 3000);
							} else {
								hui.toast("开始升级失败!");
							}
						}, function(err) {
							hui.closeLoading();
//							alert(err);
							console.log("err---"+err);
						});
					},

					updateing: function(index) {
						var _self = this;

						if(index > _self.packageCount - 1) {
							setTimeout(function() {
								_self.endUpdate();
							}, 500)
							return;
						}

						_self.updating = true;
						var command = "A3" + _self.packageList[index]
						_self.bleConnect.writeData(command, function(ret) {
							//console.log("升级返回数据:"comFull+ ret);
							if(checkCommand(ret)) {
								_self.packageIndex = index;
								//var precent =parseInt( index/_self.packageCount*100 );		
								setPrecent(_self.getPrecent());
								//vm.updateText = vm.updateText.concat(command.toUpperCase());
								_self.errCount = 0;
								setTimeout(function() {
									_self.updateing(index + 1);
								}, 20);

							} else {
								_self.updateError(index, "返回指令:" + ret)
							}
						}, function(err) {
							hui.closeLoading();
							_self.updateError(index, err);
							//alert(err);
							console.log("updateing err---"+err);

						});

					},

					updateError: function(index, msg) {
						var _self = this;
						console.log("升级错误:" + index + "|" + msg);
						if(_self.errCount < 3) {
							_self.errCount++;
							setTimeout(function() {
								_self.updateing(index);
							}, 100);
						} else {
							_self.updating = false;
							alert("升级失败,请手动结束," + msg)
						};
					},

					endUpdate: function() {
						var _self = this;
						if(!this.Tid || this.Tid.length == 0) {
							hui.toast("请先获取终端编号");
							return;
						}

						if(!this.bleConnect) {
							this.bleConnect = plus.blecontroler;
						}

						var command = "5A3009" + this.Tid + "00";
						console.log("结束升级" + command);
						this.bleConnect.writeData(command, function(ret) {
							console.log("结束升级返回数据:" + ret);
							if(checkCommand(ret)) {
								_self.updating = false;
								setPrecent(100);
								hui.toast("版本升级成功,升级完成!");
								hui.loading("正在重新连接蓝牙...");
								setTimeout(function() {
									_self.reconnect();
								}, 1500);

							} else {
								hui.toast("结束升级失败!");
							}
						}, function(err) {
							_self.updating = false;
							hui.closeLoading();
//							alert(err);
							console.log('endUpdate err--'+err);
						});
					},

					reconnect: function() {
						var _self = this;
						_self.bleConnect.connectBle(_self.mac, function(ret) {
							hui.closeLoading();
							hui.toast("连接蓝牙设备成功");
							_self.getNowVersion();

						}, function(err) {
							hui.upToast("重新连接设备失败!");

						})

					}

				}
			});

			//检查指令是否成功
			function checkCommand(command) {
				return command.toUpperCase().indexOf('5A2308') >= 0;
			}


			//获得传入的?key=.value 参数
			function getValue(key) {
				var str = window.location.search; //location.search是从当前URL的?号开始的字符串  
				var value = "";
				if(str.indexOf(key) != -1) {
					var pos_start = str.indexOf(key) + key.length + 1;
					var pos_end = str.indexOf("&", pos_start);
					if(pos_end == -1) {
						value = str.substring(pos_start);
					} else {
						value = str.substring(pos_start, pos_end);
					}
				}
				return value;
			}

			
			
		</script>
	</body>

	</script>
	</body>

</html>